package org.breathe.dynamic.thread.pool.starter.cloud.nacos.refresh;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.breathe.dynamic.thread.pool.core.refresh.AbstractRefresher;
import org.breathe.dynamic.thread.pool.core.spring.ThreadPoolCreator;
import org.breathe.thread.pool.common.entity.BreatheDtpProperties;
import org.breathe.thread.pool.common.enums.ConfigFileTypeEnum;
import org.breathe.thread.pool.common.utils.NacosUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * nacos刷新配置
 * @author: breathe
 * @createTime: 2025-04-13
 */
@Slf4j
public class CloudNacosRefresher  extends AbstractRefresher implements Listener, InitializingBean {
    private static final ThreadPoolExecutor EXECUTOR = ThreadPoolCreator.createCommonFast("nacos-listener");

    private ConfigFileTypeEnum configFileType;

    @Autowired
    private NacosConfigManager nacosConfigManager;
    
    @Autowired
    private BreatheDtpProperties breatheDtpProperties;

    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    @Autowired
    private Environment environment;
    @Override
    public Executor getExecutor() {
        return EXECUTOR;
    }

    @Override
    public void receiveConfigInfo(String s) {
        refresh(s, configFileType);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        BreatheDtpProperties.Nacos nacos = breatheDtpProperties.getNacos();
        configFileType = NacosUtil.getConfigType(breatheDtpProperties,
                ConfigFileTypeEnum.of(nacosConfigProperties.getFileExtension()));
        String dataId = NacosUtil.deduceDataId(nacos, environment, configFileType);
        String group = NacosUtil.getGroup(nacos, nacosConfigProperties.getGroup());
        try {
            nacosConfigManager.getConfigService().addListener(dataId, group, this);
            log.info("breathe dynamicTp refresher, add listener success, dataId: {}, group: {}", dataId, group);
        } catch (NacosException e) {
            log.error("breathe dynamicTp refresher, add listener error, dataId: {}, group: {}", dataId, group, e);
        }
    }
}
